// pages/address/index.js
const app = getApp()
Page({
	data: {
		url: app.globalData.url,
		addressList: undefined
	},
	// 用户登录
	to_login() {
		const appid = "wx8efd630c320af804"
		const secret = "1174ac6e704e3ca93e12eb5b5eeec336"
		const that = this
		wx.login({
			success(res) {
				if (res.code) {
					// 将登录凭证发送到服务端
					wx.request({
						url: 'https://api.weixin.qq.com/sns/jscode2session?appid='
							+ appid + '&secret=' + secret + '&js_code=' + res.code
							+ '&grant_type=authorization_code',
						method: 'GET',
						success(res) {
							wx.request({
								url: that.data.url + "/user/login",
								data: {
									openid: res.data.openid
								},
								success(res) {
									if (res.data.code == 1) {
										wx.setStorageSync("user", res.data.result)
										that.setData({ user: res.data.result })
										wx.showToast({ title: '登录成功' })
										const pages = getCurrentPages()
										const perpage = pages[pages.length - 1]
										perpage.onLoad()
									}
								}
							})
						}
					})
				}
			}
		})
	},
	onShow() {
		const user = wx.getStorageSync("user")
		if (user) {
			this.setData({ user })
		} else {
			this.to_login()
		}
		const that = this
		wx.showLoading({
			title: '请稍等...'
		})
		wx.request({
			url: that.data.url + "/address/all",
			method: "GET",
			data: { uid: that.data.user.id },
			success(res) {
				if (res.data.code === 1) {
					that.setData({ addressList: res.data.result })
					wx.hideLoading({
						success: (res) => { },
					})
				}
			}
		})
	},
	addAddr() {
		wx.navigateTo({
			url: '/pages/addAddr/index',
		})
	},
	edit(e) {
		wx.navigateTo({
			url: '/pages/addAddr/index?address=' + JSON.stringify(e.currentTarget.dataset.address),
		})
	},
	checkAddress(e) {
		let pages = getCurrentPages();
		let prevPage = pages[pages.length - 2];//上一个页面
		prevPage.setData({
			address: e.currentTarget.dataset.address
		})
		let list = prevPage.data.orderList
		list.forEach((order) => {
			order.addressId = e.currentTarget.dataset.address.id,
			wx.request({
				url: prevPage.data.url + "/order/edit",
				method: "POST",
				data: order,
				success(res) {
					if (order.id == list[list.length - 1].id) {
						wx.navigateBack({
							delta: 0,
						})
					}
				}
			})
		})
	}
})